<template>
  <div>
    <el-form ref="form" :rules="rules" :model="formData" label-width="100px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="发布位置:">
            <el-select v-model="formData.location" placeholder="请选择">
              <el-option
                v-for="item in locationOptions"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态:">
            <el-select v-model="formData.status" placeholder="请选择">
              <el-option
                v-for="item in statusOptions"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="title:" prop="title">
            <el-input v-model="formData.title"></el-input>
          </el-form-item>

        </el-col>

        <el-col :span="12">
          <el-form-item label="关键词:" prop="keyword">
            <el-input v-model="formData.keyword"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="来源:" prop="source">
            <el-input v-model="formData.source"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="来源Url:" prop="fromUrl">
            <el-input v-model="formData.fromUrl"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="发布时间:" prop="publishDate">
            <el-date-picker
              v-model="formData.publishDate"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions1">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="新闻描述:" prop="description">
            <el-input type="textarea" v-model="formData.description" :rows="1"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="新闻标题:" prop="briefTitle">
            <el-input v-model="formData.briefTitle"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="block-item">
            <p>正文内容:</p>
            <vue-ueditor ueditorPath="//cdn.cd121.com/ueditor/1.4.3.3/"
                         @ready="editorReadyHandler"
                         :ueditorConfig="editorConfig"/>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div class="btn-group-wrapper top">
      <el-button type="primary" icon="upload" @click="releaseHandler">发布</el-button>
      <el-button type="primary" @click="previewHandler">预览</el-button>
      <el-button type="primary" icon="document" @click="draftHandler">草稿</el-button>
    </div>
  </div>
</template>
<script>

  import { mapActions, mapGetters } from 'vuex'

  import moduleStore from './bll/store'
  import store from '../../store'
  import assignDeep from 'assign-deep';
  (!store.state.sysNewsBroadcast) && store.registerModule('sysNewsBroadcast', moduleStore)

  import VueUeditor from 'vue-ueditor';
  import { forNewsAdd as editorConfig } from '../../common/editor.config'
  import stringUtil from '../../common/stringUtil';
  import dateUtil from '../../common/dateUtil';
  export default{
    data() {
      return {
        pickerOptions1: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        rules: {
          title: [
            {required: true, message: '请输入title', trigger: 'blur'}
          ],
          keyword: [
            {required: true, message: '请输入关键词', trigger: 'blur'}
          ],
          briefTitle: [
            {required: true, message: '请输入新闻标题', trigger: 'blur'}
          ]
        },
        searchText: '',
        locationOptions: [
          {
            value: 'APP',
            label: 'APP'
          },
          {
            value: 'PC',
            label: 'PC'
          }
        ],
        statusOptions: [
          {
            value: '上线',
            label: '上线'
          },
          {
            value: '下线',
            label: '下线'
          }
        ],
        formData: {
          //id: 0,
          title: '',
          source: '',
          fromUrl: '',
          publishDate: '',
          location: '',
          status: '',
          publisher: '',
          keyword: '',
          content: '',
          briefTitle: '',
          description: ''
        },
        editorConfig: editorConfig,
        editor: null
      }
    },
    components: {VueUeditor},
    mounted() {
      let pageModel = this.getNewsPageModel;
      if (pageModel === 'UPDATE') {
        this.formData = assignDeep({}, this.getEditingNews);
      } else {
        this.formData.publishDate = (new Date()).getTime();
      }
    },
    computed: {
      ...mapGetters(['getNewsPageModel', 'getEditingNews'])
    },
    methods: {
      ...mapActions(['releaseNews', 'updateNews']),
      editorReadyHandler(editorInstance) {
        this.editor = editorInstance;
        if (this.getNewsPageModel === 'UPDATE') {
          this.editor.setContent(this.formData.content);
        }
      },
      getEditorContentHandler() {
        if (this.editor) {
          this.formData.content = this.editor.getContent();
        }
      },
      resetHandler() {
        this.$refs.form.resetFields();
      },
      /*
       releaseHandler() {
       let self = this;
       let data = {};
       this.getEditorContentHandler();
       //不传多余信息
       let formData = assignDeep({}, this.formData);
       data.publishDate = dateUtil.dateToTimeString(formData.publishDate);
       data.title = formData.title;
       data.location = formData.location;
       data.status = formData.status;
       data.keyword = formData.keyword;
       data.content = formData.content;
       data.publisher = store.state.loginUser.userName;
       this.getNewsPageModel === 'UPDATE' && (data.id = formData.id);
       formData.source && (data.source = formData.source);
       formData.fromUrl && (data.fromUrl = formData.fromUrl);
       this.$refs.form.validate((valid) => {
       if (stringUtil.isEmpty(data.publishDate) || stringUtil.isEmpty(data.content) || stringUtil.isEmpty(data.location)) {
       valid = false;
       }
       if (valid) {
       self[self.getNewsPageModel === 'ADD' ? 'releaseNews' : 'updateNews'](data).then(() => {
       //self.disable();
       if (self.getNewsPageModel === 'ADD') {
       self.resetHandler();
       self.$message.success('添加新闻成功!');
       } else {
       self.$message.success('修改新闻成功!');
       }
       setTimeout(function () {
       self.$router.push('/newsBroadcast/index');
       }, 1000);
       })
       } else {
       this.$message({
       showClose: true,
       message: '请检查是否有未填项。',
       type: 'error'
       });
       return false;
       }
       });
       },
       */
      releaseHandler() {
        this.verifyData(this.createOrUpdate);
      },
      verifyData(callback) {
        let self = this;
        let data = {};
        this.getEditorContentHandler();
        //不传多余信息
        let formData = assignDeep({}, this.formData);
        data.publishDate = dateUtil.dateToTimeString(formData.publishDate);
        data.title = formData.title;
        data.location = formData.location;
        data.status = formData.status;
        data.keyword = formData.keyword;
        data.content = formData.content;
        data.publisher = store.state.loginUser.userName;
        data.briefTitle = formData.briefTitle;
        formData.description && (data.description = formData.description);
        this.getNewsPageModel === 'UPDATE' && (data.id = formData.id);
        formData.source && (data.source = formData.source);
        formData.fromUrl && (data.fromUrl = formData.fromUrl);
        this.$refs.form.validate((valid) => {
          if (stringUtil.isEmpty(data.publishDate) || stringUtil.isEmpty(data.content) || stringUtil.isEmpty(data.location)) {
            valid = false;
          }
          if (valid) {
            callback(data, self);
          } else {
            this.$message({
              showClose: true,
              message: '请检查是否有未填项。',
              type: 'error'
            });
            return false;
          }
        });
      },
      createOrUpdate(data, self) {
        self[self.getNewsPageModel === 'ADD' ? 'releaseNews' : 'updateNews'](data).then(() => {
          //self.disable();
          if (self.getNewsPageModel === 'ADD') {
            self.resetHandler();
            self.$message.success('添加新闻成功!');
          } else {
            self.$message.success('修改新闻成功!');
          }
          setTimeout(function () {
            self.$router.push('/newsBroadcast/index');
          }, 1000);
        })
      },
      draftHandler() {
        this.$message.warning('草稿功能暂未开放')
        //this.getEditorContentHandler();
        //TODO 如果是修改的状态下，保存为草稿的逻辑
      },
      previewHandler() {
        function saveDataAndOpenPage (data) {
          let text = {
            type: 'news',
            data: data
          }
          window.localStorage.setItem('previewText', JSON.stringify(text));
          window.open('static/preview.html');
        }

        this.verifyData(saveDataAndOpenPage);
      }
    }
  }
</script>
<style>
  .block-item {
    margin-bottom: 20px;
  }

  .block-item p {
    font-size: 14px;
    color: #48576a;
    margin-top: 0;
  }
</style>
